//
//  Actor.m
//  Box2DTest
//
//  Created by David Wagner on 21/06/2009.
//  Copyright 2009 Zygote Commando. All rights reserved.
//

#import "Actor.h"

const GLfloat squareVertices[] = {
-1.0f, -1.0f,
1.0f,  -1.0f,
-1.0f,  1.0f,
1.0f,   1.0f,
};

const GLubyte squareColorsA[] = {
72,   49, 102, 255,
35,     37,   127,   255,
180,   230, 255, 255,
79, 209,   229, 255,
};

const GLubyte squareColorsB[] = {
255,   49, 102, 255,
255,     37,   127,   255,
255,   230, 255, 255,
255, 209,   229, 255,
};

@interface Actor ()

@property (assign, nonatomic) b2Body* body;
@property (assign, nonatomic) b2World* world;

@end


@implementation Actor

@synthesize body;
@synthesize world;
@synthesize theOne;

- (void)setTheOne:(BOOL)value
{
	theOne = value;
	if( theOne )
	{
		colours = squareColorsB;
	}
	else
	{
		colours = squareColorsA;
	}
}

- (void)dealloc
{
	body->SetUserData(nil);
	world->DestroyBody(body);
	
	self.body = nil;
	self.world = nil;
	
	[super dealloc];
}

- (NSString *) description
{
	return [NSString stringWithFormat:@"[Actor %p]", self ];
}

- (void)setX:(float)x Y:(float)y
{
	b2Vec2 vector( x, y );
	body->SetXForm(vector,0);
}

- (void)setLinearVelocityX:(float)x Y:(float)y
{
	b2Vec2 vector( x, y );
	body->SetLinearVelocity(vector);
}

- (id)initWithWorld:(b2World*)newWorld
{
	self.theOne = NO;
	self.world = newWorld;
	
	b2BodyDef bodyDef;
	bodyDef.userData = self;
	body = world->CreateBody(&bodyDef);
	
	b2PolygonDef shapeDef;
	shapeDef.SetAsBox(fabs(squareVertices[0]), fabs(squareVertices[0]));
	shapeDef.density = 0.01f;
	shapeDef.friction = 0.2f;
	shapeDef.restitution = 0.7f;
	
	body->CreateShape(&shapeDef);
	body->SetMassFromShapes();
	//body->SetBullet(true);
	
	return self;
}

- (void) draw
{
	b2Vec2 position = body->GetPosition();
	float32 angle = body->GetAngle();
	
	glPushMatrix();

    glLoadIdentity();
	glTranslatef(position.x, position.y, 0);
    glRotatef(angle, 0.0f, 0.0f, 1.0f);

    glVertexPointer(2, GL_FLOAT, 0, squareVertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, colours);
    glEnableClientState(GL_COLOR_ARRAY);
    
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
	
	glPopMatrix();
}

@end
